# 全局异常处理中间件
import functools
import time
import traceback
from typing import Any
from aiohttp import web

from src.dicom_viewer_be_mock_xiaosai.common.exception import ValidationError
from src.dicom_viewer_be_mock_xiaosai.utils.logger import logger


class APIResponse:

    @staticmethod
    def success(data: Any = None, message: str = "操作成功", code: int = 1):
        """成功响应"""
        return web.json_response({
            "success": True,
            "code": code,
            "message": message,
            "data": data,
            "timestamp": int(time.time() * 1000)
        }, status=200)

    @staticmethod
    def error(message: str = "操作失败", code: int = 0, data: Any = None, status: int = 200):
        """错误响应"""
        return web.json_response({
            "success": False,
            "code": code,
            "message": message,
            "data": data,
            "timestamp": int(time.time() * 1000)
        }, status=status)




def api_response(func):
    """API 响应装饰器 - 增强错误处理"""

    @functools.wraps(func)
    async def wrapper(request: web.Request) -> web.StreamResponse:
        try:
            result = await func(request)

            # 如果已经是 web.Response 对象，直接返回
            if isinstance(result, web.Response):
                return result

            # 如果是字典，包装成标准响应
            if isinstance(result, dict):
                return APIResponse.success(data=result)

            # 其他情况
            return APIResponse.success(data=result)

        except ValidationError as e:
            return APIResponse.error(message=str(e), code=400)


        except ValueError as e:
            # 记录详细的错误信息
            error_info = {
                "function": func.__name__,
                "path": request.path,
                "method": request.method,
                "error_type": "ValueError",
                "error_message": str(e),
                "traceback": traceback.format_exc()
            }

            logger.warning(f"ValueError in {func.__name__}: {error_info}")
            logger.info(f"=== ValueError in {func.__name__} ===")
            logger.info(f"Path: {request.path}")
            logger.info(f"Error: {str(e)}")
            logger.info(f"Traceback:\n{traceback.format_exc()}")
            logger.info("=" * 50)

            return APIResponse.error(message=str(e), status=400)

        except Exception as e:
            # 记录详细的错误信息
            error_info = {
                "function": func.__name__,
                "path": request.path,
                "method": request.method,
                "error_type": type(e).__name__,
                "error_message": str(e),
                "traceback": traceback.format_exc()
            }

            logger.error(f"Exception in {func.__name__}: {error_info}")
            logger.info(f"=== Exception in {func.__name__} ===")
            logger.info(f"Path: {request.path}")
            logger.info(f"Error Type: {type(e).__name__}")
            logger.info(f"Error Message: {str(e)}")
            logger.info(f"Full Traceback:\n{traceback.format_exc()}")
            logger.info("=" * 50)

            return APIResponse.error(message=str(e), code=500)

    return wrapper
